﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class UserPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (!HttpContext.Current.User.Identity.IsAuthenticated)
            //    Response.Redirect("~/Default.aspx");             
            
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.UserPage_PageTitle;
            //this.Title = GND.ReturnAppTitle();
            this.LanguageHiddenField.Value = ou.Language;

            //if (ou.TeamId == "Null")
            //    Response.Redirect("~/GeneralMessage.aspx?MessageString=M74ggdizz5wfeh");

            string Id = null;
            if (Request.QueryString["Id"] != null)
            {
                Id = Request.QueryString["Id"].ToString();
                UserIdHiddenField.Value = Id;
                ReportHyperlink.NavigateUrl = "~/ViewDuplicateConnections.aspx?UserId=" + Id;
            }
            else
                Response.Redirect("GeneralMessage.aspx?MessageString=Q4OQX1EOTHJA");

            if (Request.QueryString["GuestbookMessage"] != null)
            {
                this.WallMessageLabel.Text = Request.QueryString["GuestbookMessage"];
            }

            #region SetUserDetails
            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand("Nivdal_GetUserDetails", conn);
            SqlDataReader reader;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier);
            cmd.Parameters["@UserId"].Value = new Guid(Id);
            try
            {
                conn.Open();
                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                    while (reader.Read())
                    {
                        this.UserNameLabel.Text = reader.GetString(0);
                        if (!reader.IsDBNull(1))
                            this.TeamLinkButton.NavigateUrl = "TeamHomePage.aspx?TeamId=" + reader.GetDecimal(1).ToString();
                        this.TeamLinkButton.Text = reader.GetString(2);
                        this.FlagButton.PostBackUrl = "Country.aspx?Id=" + reader.GetDecimal(3).ToString();
                        this.FlagButton.ToolTip = reader.GetString(4);
                        this.FlagButton.ImageUrl = "~/Images/Flags/" + reader.GetString(5);
                        this.PreferredLanguageTitleLabel.Text = Resources.Resource.UserPage_PreferredLanguageTitleLabel + " " + reader.GetString(6);
                        this.UserIconImage.ToolTip = reader.GetString(7);
                        this.JoinedLabel.Text = Resources.Resource.UserPage_JoinedLabel + " " + reader.GetString(8);
                        this.UserIconImage.ImageUrl = "Images/Icons/" + reader.GetString(9);
                        this.UserPicture.ImageUrl = reader.GetString(10);
                        if (!reader.IsDBNull(11))
                        {
                            this.LastLoginLabel.Text = Resources.Resource.Global_LastLogin + ": " + reader.GetString(11);
                        }
                        else
                        {
                            this.LastLoginLabel.Text = Resources.Resource.UserPage_NotLatelyLoginLabel;
                        }
                        this.ForumRankImage.ImageUrl = NumPostImage(reader.GetDecimal(13));
                        this.ForumRankImage.ToolTip = reader.GetDecimal(13).ToString() + " " + Resources.Resource.UserPage_ForumPosts;
                        this.IsPremiumImage.Visible = reader.GetBoolean(14);
                        this.IsOfflineImage.Visible = !reader.GetBoolean(15);
                        this.IsOnlineImage.Visible = reader.GetBoolean(15);
                        if (reader.GetDecimal(18) != 0)
                        {
                            NationalCoachImage.NavigateUrl = "~/NationalTeam.aspx?Id=" + reader.GetDecimal(18).ToString();
                            NationalCoachImage.ToolTip = Resources.Resource.Global_Manager + " " + reader.GetString(19);
                            NationalCoachImage.ImageUrl = "~/Images/Flags/" + reader.GetString(20);
                        }
                        else
                            NationalCoachImage.Visible = false;
                    }
            }
            catch
            {
                Response.Redirect("~/Default.aspx");
            }
            finally
            {
                conn.Close();
            }
            #endregion SetUserDetails

            // Id - the user who's page this is 
            // UserId - the connected user

            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                this.IsFriendImage.Visible = GND.ReadNivdalBoolData("User1", "User2", "Nivdal_FriendshipAreUsersFriendsProc", Id, ou.UserId);

                this.SuggestFriendshipImage.Visible = GND.ReadNivdalBoolData("Friend1", "Friend2", "Nivdal_FriendshipCanUserSuggestFriendship", ou.UserId, Id);
                this.FriendshipSuggestionPendingImage.Visible = GND.ReadNivdalBoolData("User1", "User2", "Nivdal_FriendshipIsSuggestionPending", ou.UserId, Id);
            }
            else
            {
                this.IsFriendImage.Visible = false;
                this.SuggestFriendshipImage.Visible = false;
                this.FriendshipSuggestionPendingImage.Visible = false;
            }


            //if (IsPostBack)
            //{
            //    this.GuestBookDataSource.SelectParameters.Clear();
            //    this.MutualFriendsDataSourse.SelectParameters.Clear();
            //    this.FriendsListDataSource.SelectParameters.Clear();
            //    this.UserForumsDataSourse.SelectParameters.Clear();                
            //}

            if (!IsPostBack)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    this.MutualFriendsDataSourse.SelectParameters.Add("User1Id", ou.UserId);
                    this.MutualFriendsDataSourse.SelectParameters.Add("User2Id", Id);
                    this.MutualFriendsDataSourse.SelectParameters.Add("ShowAll", "0");
                }
                else
                {
                    ComposeMessageImageButton.Visible = false;
                }
                this.UserForumsDataSourse.SelectParameters.Add("UserId", Id);
                this.FriendsListDataSource.SelectParameters.Add("UserId", Id);
                this.FriendsListDataSource.SelectParameters.Add("ShowAll", "0");
                this.GuestBookDataSource.SelectParameters.Add("UserId", Id);
                if(HttpContext.Current.User.Identity.IsAuthenticated)
                    this.GuestBookDataSource.SelectParameters.Add("ShownFor", ou.UserId);
                this.NewsPaperPrivsDataSourse.SelectParameters.Add("UserId", Id);
                this.NewsPaperPrivsDataSourse.SelectParameters.Add("ReaderId", ou.UserId);
                this.QnATipsSQLDataSource.SelectParameters.Add("UserId", Id);                
                this.BehaviourReportsDataSource.SelectParameters.Add("UserId", Id);
                this.BehaviourReportsPanel.Visible = ((ou.UserId == Id) || (ou.UserAccessLevel == "4") || (ou.UserAccessLevel == "5"));
            }
            //this.LinkToUserInfoPanel.Visible = (Id == UserId);
            this.LockUserImageButton.Visible = (ou.UserAccessLevel == "5");
            this.ReportHyperlink.Visible = (ou.UserAccessLevel == "5");
            this.AdminPanel.Visible = (ou.UserAccessLevel == "5");
            this.QnAEditPanel.Visible = (ou.UserAccessLevel == "5");

            this.WallMessagePanel.Visible = (this.WallMessageLabel.Text.Length > 0);
            this.WriteOnWallPanel.Visible = (ou.IsPremium && (ou.UserId.ToLower() != Id.ToLower()));
            if (ou.UserId == Id)
                this.UserPicture.PostBackUrl = "~/Preferences.aspx";

            
            if (ou.UserId != null)
            {
                this.UserIsTheConnectedUserPanel.Visible = (ou.UserId.ToLower() != Id.ToLower());
            }
            else
            {
                UserIsTheConnectedUserPanel.Visible = false;
            }

            if (ou.IsPremium)
            {
                this.BookmarkButton.Visible = true;
            }
            else
            { this.PrivateForumsPanel.Visible = false; }

        }

        protected void SendMailLinkButtonButton_Click(object sender, EventArgs e)
        {
            string Id = UserIdHiddenField.Value;
            Response.Redirect("ComposeMail.aspx?ToId=" + Id + "&IsReplyTo=0");
        }

        protected void BookmarkButton_Click(object sender, EventArgs e)
        {
            String Id = UserIdHiddenField.Value;
            OnlineUser ou = (OnlineUser)Session["User"];

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_BookmarkUser";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_UserId = new SqlParameter();
            dbParam_UserId.ParameterName = "@UserId";
            dbParam_UserId.Value = ou.UserId;
            dbParam_UserId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_UserId);

            SqlParameter dbParam_BookmarkedPlayer = new SqlParameter();
            dbParam_BookmarkedPlayer.ParameterName = "@BookmarkedUser";
            dbParam_BookmarkedPlayer.Value = Id;
            dbParam_BookmarkedPlayer.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_BookmarkedPlayer);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {
                dbConnection.Open();
                dbCommand.ExecuteScalar();
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + dbParam_Answer.Value.ToString());
            }
            catch (Exception SQLDBException)
            {
                this.ErrorLabel.Text = Convert.ToString(SQLDBException);
            }

            finally
            {
                dbConnection.Close();
            }

        }

        protected bool ForumIconName(decimal MembershipType)
        {
            bool ReturnValue;
            if (MembershipType == 1)
                ReturnValue = false;
            else
                ReturnValue = true;

            return (ReturnValue);
        }

        protected string NumPostImage(decimal NumPosts)
        {
            string FileName = "";

            if (NumPosts >= 5000) FileName = "~/Images/Icons/forum05.jpg";
            else if (NumPosts >= 1000) FileName = "~/Images/Icons/forum04.jpg";
            else if (NumPosts >= 200) FileName = "~/Images/Icons/forum03.jpg";
            else if (NumPosts >= 50) FileName = "~/Images/Icons/forum02.jpg";
            else FileName = "~/Images/Icons/forum01.jpg";

            return (FileName);
        }

        protected void BecomeFriendButtonClick(object sender, ImageClickEventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string Answer;
            Answer = GND.ReadNivdalStringData("Friend1", "Friend2", "Nivdal_FriendshipSuggestFriendship", ou.UserId, UserIdHiddenField.Value);
            Response.Redirect("~/Friends.aspx?Message=" + Answer);
        }

        protected void DeleteWallEntry(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteEntry")
            {
                try
                {
                    string EntryId = e.CommandArgument.ToString();
                    string Answer;
                    GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                    OnlineUser ou = (OnlineUser)Session["User"];
                    Answer = GND.ReadNivdalStringData("WallEntryId", "UserId", "Nivdal_WallDeleteWallEntry", EntryId, ou.UserId);
                    WallMessageLabel.Text = Answer;
                }
                catch {  }
            }

            GuestBookListView.DataBind();
        }

        protected void SubmitToWallButtonClick(object sender, EventArgs e)
        {
            string EntryText = this.WriteOnWallTextBox.Text.Trim();
            OnlineUser ou = (OnlineUser)Session["User"];
            if (EntryText.Length > 0)
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                string Answer = GND.ReadNivdalStringData("WallOwner", "ComposedBy", "Text", "Nivdal_WallAddWallEntry", this.UserIdHiddenField.Value,
                                                        ou.UserId, EntryText);
                WallMessageLabel.Text = Answer;
                WriteOnWallTextBox.Text = "";
                GuestBookListView.DataBind();
            }
        }


        protected string DeleteGuestbookOnClientClick()
        {
            return ("return confirm('" + Resources.Resource.TeamHomePage_WallDeleteButtonOnClientClick + "');");
        }

        protected string LockUserOnClientClick()
        {
            return ("return confirm('" + Resources.Resource.UserPage_LockUserOnClientClick + "');");
        }
        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        protected void LockUser(object sender, ImageClickEventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            GND.ExecNivdalSQL("UserId", "Nivdal_LockUser", UserIdHiddenField.Value);
            Response.Redirect("~/AdminApproveUsers.aspx");
        }

        protected string tryal(object t)
        {
            string tSrc = t.ToString();
            return GlobalFunctions.LightEncodeHtmlFromText(tSrc);
        }

        protected void FriendsListViewDataBound(Object sender, EventArgs e)
        {
            FriendsLinkButton.Visible = (FriendsListView.Items.Count == 10);            
        }

        protected void MutualFrendsListViewDataBound(Object sender, EventArgs e)
        {
            MutualFriendsMoreLinkButton.Visible = (MutualFriendsListView.Items.Count == 10);

        }

        protected void ShowMoreFriends(Object sender, EventArgs e)
        {
            this.FriendsListDataSource.SelectParameters.Clear();
            this.FriendsListDataSource.SelectParameters.Add("UserId", UserIdHiddenField.Value);
            this.FriendsListDataSource.SelectParameters.Add("ShowAll", "1");            
            FriendsListView.DataBind();
        }

        //protected void Button2_Click(object sender, EventArgs e)
        //{
        //    this.PreviewLabel.Text = GlobalFunctions.EncodeHtmlFromText(this.WriteOnWallTextBox.Text.Trim());
        //}

        protected void MutualFriendsRefresh(Object sender, EventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            this.MutualFriendsDataSourse.SelectParameters.Clear();
            this.MutualFriendsDataSourse.SelectParameters.Add("User1Id", ou.UserId);
            this.MutualFriendsDataSourse.SelectParameters.Add("User2Id", UserIdHiddenField.Value);
            this.MutualFriendsDataSourse.SelectParameters.Add("ShowAll", "1");
            MutualFriendsListView.DataBind();
        }


    }
}